package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import com.myLogger.LogException;
import com.myLogger.LoggerManager;

@ManagedBean
@ApplicationScoped
public class Log {
	private LoggerManager logger;
	private ResourceBundle general;
	private String logDirName;
	private String logName;
	
	public Log() {
		general = ResourceBundle.getBundle("properties.general");
		
		//Create main logger
		logger = createGeneralLogger();
	}

	/**
	 * Create the main logger
	 * @return
	 */
	private LoggerManager createGeneralLogger() {
		//Get info from properties file
		logDirName 							= general.getString(CachedInfo.LOG_DIR);
		SimpleDateFormat 	sdfLogFileName 	= new SimpleDateFormat(general.getString(CachedInfo.LOG_FILE_DATE_FORMAT));		  				
		String 				logLevelStr		= general.getString(CachedInfo.LOG_LEVEL);
		int 				logLevel 		= Integer.parseInt(logLevelStr);
		String				logDebugModeStr = general.getString(CachedInfo.LOG_DEBUG_MODE);
		boolean				logDebugMode	= Boolean.parseBoolean(logDebugModeStr);

		File 				logDir 			= new File(logDirName);
		
		logDir.mkdir();

		//Create the logger
		logName 							= "log_" + sdfLogFileName.format(new Date()) + "_main.log";

		LoggerManager logger = null;
		try {
			logger = new LoggerManager(logDirName, logName, logLevel);

			//Setting logger options
			logger.setDebugMode(logDebugMode);
			logger.setTimeStampFormat(new SimpleDateFormat(general.getString(CachedInfo.LOG_DATE_FORMAT)));
		} catch (LogException e) {
			System.err.println("Error in create log file");
			e.printStackTrace();
		}
		
		return logger;
	}

	public String getLogContent() throws IOException {
		final int bufferLenght = 4096;
		byte[] buffer = new byte[bufferLenght];
		StringBuilder content = new StringBuilder();
		
		FileInputStream fis = null;
		try {
			 fis = new FileInputStream(logDirName + "/" + logName);
		} catch (FileNotFoundException e) {
			logger.logError(1, this.getClass() + ". Error reading log file");
			return null;
		}
		
		try {
			while (fis.read(buffer) != -1)
			{
				content.append(buffer);
				System.out.println(buffer);
			}
		} catch (IOException e) {
			logger.logError(1, this.getClass() + ". Error reading log file");
			return null;
		}
		
		return content.toString();
	}

	public LoggerManager getLogger() {
		return logger;
	}

	public void setLogger(LoggerManager logger) {
		this.logger = logger;
	}

	public ResourceBundle getGeneral() {
		return general;
	}

	public void setGeneral(ResourceBundle general) {
		this.general = general;
	}
}
